Ext.extend(Ext.Panel, {
	layout : 'border',
	defaults : {
		split : true
	},

	initComponent : function() {
		var westPanel = this.getWestPanel();
		var centerPanel = this.getCenterPanel();
		this.items = [westPanel, centerPanel];

		this.columnTypeStore = new Ext.data.JsonStore({
			autoLoad : true,
			url : contextPath + '/model/getmodelcolumntype',
			root : 'rows',
			fields : ['name', 'value']
		});

		T.superclass.initComponent.call(this, arguments);
	},

	getWestPanel : function() {
		var panel;
		if (this.rendered) {
			panel = this.get(0);
		} else {
			var loader = new Ext.tree.TreeLoader({
				url : contextPath + '/model/getmodeltree',
				listeners : {
					beforeload : function(l, n, c) {
						l.baseParams.type = n.attributes.type;
					}
				}
			});
			panel = new Ext.tree.TreePanel({
				region : 'west',
				collapsible : true,
				width : 200,
				margins : '5 0 5 5',
				cmargins : '5 5 5 5',
				collapseFirst : false,
				autoScroll : true,
				split : true,
				title : '模型',
				tools : [{
					id : 'refresh',
					handler : function(e, toolEl, panel, tc) {
						panel.getRootNode().reload(Ext.emptyFn());
					}
				}],
				loader : loader,
				root : new Ext.tree.AsyncTreeNode({
					id : '_root',
					text : '模型对象',
					expanded : true,
					type : 'group'
				}),
				listeners : {
					contextmenu : this.onContextMenu,
					click : this.onTreeClick,
					scope : this
				}
			});
		}
		return panel;
	},
	
	onContextMenu : function(node, e) {
		node.select();

		var tree = node.getOwnerTree();
		var menu = tree.contextMenu;
		if (!menu) {
			menu = tree.contextMenu = new Ext.menu.Menu({
				items : [{
					ref : 'newModelGroupBtn',
					text : '新建模型组',
					handler: function(){
						this.showModelWindow('group');
					},
					scope: this
				}, {
					ref : 'newModelBtn',
					text : '新建模型对象',
					handler: function(){
						this.showModelWindow('model');
					},
					scope: this
				}, {
					ref : 'newModelColumnBtn',
					text : '新建模型列',
					handler: function(){
						this.showModelWindow('column');
					},
					scope: this
				}, {
					ref : 'separatorBtn',
					xtype : 'menuseparator'
				}, {
					ref : 'createTableBtn',
					text : '构库',
					handler: function(){
						this.buildModel(node.id, node.attributes.type);
					},
					scope: this
				}, {
					ref : 'dropTableBtn',
					text : '取消构库',
					handler: function(){
						this.dropModel(item, e);
					},
					scope: this
				}, {
					ref : 'delModelBtn',
					text : '删除',
					handler: function(item){
						this.deleteModel(item);
					},
					scope: this
				}]
			});
		}

		/*
		 * var newModelGroupBtn = menu.get('newModelGroupBtn'); var newModelBtn =
		 * menu.get('newModelBtn'); var newModelColumnBtn =
		 * menu.get('newModelColumnBtn'); var delModelBtn =
		 * menu.get('delModelBtn'); var createTableBtn =
		 * menu.get('createTableBtn'); var dropTableBtn =
		 * menu.get('dropTableBtn'); var separatorBtn =
		 * menu.get('separatorBtn');
		 * 
		 * var root = node.isRoot, type = node.attributes.type;
		 * 
		 * newModelGroupBtn.setVisible(type == 'group');
		 * newModelBtn.setVisible(type == 'group');
		 * newModelColumnBtn.setVisible(type == 'model');
		 * delModelBtn.setVisible(!root); createTableBtn.setVisible(type !=
		 * 'group'); dropTableBtn.setVisible(type != 'group');
		 * separatorBtn.setVisible(!(root || type == 'column'));
		 */
		menu.contextNode = node;
		menu.showAt(e.getXY());
	},

	onTreeClick : function(node) {
		if (node.attributes.type !== 'model') {
			return;
		}
		var center = this.getCenterPanel();
		center.contextTreeNode = node;
		center.getStore().load({
			params : {
				modelId : node.id
			}
		});
	},

	getCenterPanel : function() {
		var panel;
		if (this.rendered) {
			panel = this.get(1);
		} else {
			var store = new Ext.data.JsonStore({
				url : contextPath + '/model/getmodelcolumngrid',
				root : 'rows',
				fields : ['column_id', 'column_name', 'physical_name', 'column_type',
						'column_length', 'nullable', 'default_value',
						'created', 'range', 'formatter', 'validator']
			});

			var columns = [{
				header : '是否构库',
				dataIndex : 'created',
				renderer : function(v, meta) {
					if (v === true) {
						meta.css = 'icon_column_created';
						meta.attr = 'title="已构库" style="padding-left:16px;"';
						return '已构库';
					} else {
						meta.css = 'icon_column';
						meta.attr = 'title="未构库" style="padding-left:16px;"';
						return '未构库';
					}
				}
			}, {
				header : '列名',
				dataIndex : 'column_name'
			}, {
				header : '物理名称',
				dataIndex : 'physical_name'
			}, {
				header : '数据类型',
				dataIndex : 'column_type'
			}, {
				header : '字段长度',
				dataIndex : 'column_length'
			}, {
				header : '是否可空',
				dataIndex : 'nullable'
			}, {
				header : '默认值',
				dataIndex : 'default_value'
			}, {
				header : '选择范围',
				dataIndex : 'range'
			}];
			panel = new Ext.grid.GridPanel({
				tbar : [{
					text : '新增列',
					iconCls : 'icon_column_add',
					handler : function() {
						this.showModelWindow('column');
					},
					scope : this
				}, {
					text: '构库',
					handler: function(){
						var grid = this.getCenterPanel();
						var records = grid.getSelectionModel().getSelections();
						if (records.length == 0) {
							alert('请选择一条记录！\t');
							return;
						}
						var ids = [];
						Ext.each(records, function(r){
							if (!t.get('created')) {
								ids.push(r.get('column_id'));
							}
						});
						this.buildModel(ids, 'column')
					},
					scope: this
				}],
				columnLines : true,
				store : store,
				region : 'center',
				columns : columns,
				margins : '5 5 5 0'
			});
			panel.on('afteredit', this.afterEdit);
		}
		return panel;
	},

	afterEdit : function(e) {
		var ctxNode = e.grid.contextNode;

		var params = {
			type : ctxNode.attributes.type,
			uid : ctxNode.id,
			column : e.record.id,
			value : e.value
		};

		Utils.request({
			url : contextPath + '/model/editModel'
					+ Ext.urlEncode(params, '&'),
			success : function(json, opts) {
				e.record.commit();

				// 更改树节点
				if (e.record.id == 'model_name'
						|| e.record.id == 'column_name') {
					ctxNode.setText(e.value);
				}
			}
		});
	},

	showModelWindow : function(type) {
		if (type == 'group') {
			title = '新建模型组';
		} else if (type == 'model') {
			title = '新建模型对象';
		} else if (type == 'column') {
			title = '新建模型列';
		}

		var commonItems = [{
			name : 'name',
			fieldLabel : '显示名称',
			allowBlank : false
		}, {
			name : 'physical',
			fieldLabel : '物理名称',
			allowBlank : false
		}];
		if (type == 'column') {
			commonItems.push([{
				name : 'dataType',
				hiddenName : 'dataType',
				xtype : 'combo',
				fieldLabel : '字段类型',
				typeAhead : true,
				triggerAction : 'all',
				mode : 'remote',
				store : this.columnTypeStore,
				valueField : 'value',
				displayField : 'name',
				allowBlank : false
			}, {
				name : 'columnLength',
				fieldLabel : '字段长度',
				xtype : 'numberfield',
				allowBlank : false
			}, {
				name : 'isNullable',
				fieldLabel : '是否可空'
			}, {
				name : 'defaultValue',
				fieldLabel : '默认值'
			}]);
		}

		var form = new Ext.form.FormPanel({
			bodyStyle : 'padding:15px 10px;',
			labelWidth : 80,
			labelAlign : 'left',
			defaults : {
				anchor : '-10',
				xtype : 'textfield',
				msgTarget : 'title'
			},
			items : commonItems
		});

		var win = Utils.window({
			title : title,
			height : type == 'column' ? 250 : 150,
			items : [form],
			callback : {
				fn : function(win) {
					this.addModel(win, type);
				},
				scope : this
			}
		});
	},

	addModel : function(win, type) {
		var node = this.getWestPanel().contextMenu.contextNode;
		var form = win.get(0);
		var url = contextPath + '/model/addModel';
		form.getForm().submit({
			url : url,
			params : {
				parentId : node.id,
				type : type
			},
			success : function(json) {
				node.reload();
				win.close();
			}
		});
	},

	deleteModel : function(item) {
		if (!confirm('您确定要删除吗？\t')) {
			return;
		}
		var node = item.parentMenu.contextNode;
		var url = contextPath + '/model/deleteModel';
		Utils.request({
			url : url,
			params : {
				uid : node.id,
				type : node.attributes.type
			},
			success : function(success, msg) {
				node.remove();
			}
		});
	},

	buildModel : function(ids, type) {
		if (typeof ids == 'string') {
			ids = [ids];
		}
		var url = contextPath + '/model/buildModel';
		Utils.request({
			url : url,
			params : {
				ids : ids.join(','),
				type : type
			},
			success : function(success, msg) {
				var node = this.getWestPanel().getSelectionModel().getSelectedNode();
				node.parentNode.reload();
			},
			scope: this
		});
	},

	dropModel : function(item, e) {

	}
});
